package com.t.bricks.bussiness.service.waitnote.impl;

import java.io.PrintWriter;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.t.bricks.bussiness.db.dao.waitnote.WaitNoteDao;
import com.t.bricks.bussiness.db.entity.waitnote.WaitNote;
import com.t.bricks.bussiness.db.entity.waitnote.WaitNoteSimpl;
import com.t.bricks.bussiness.service.waitnote.WaitNoteService;
import com.t.bricks.model.Log;
import com.t.bricks.model.MsgEmity;
import com.t.bricks.utils.function.date.TimeUtil;
import com.t.bricks.utils.function.json.JacksonShell;
import com.t.bricks.utils.function.thread.ThreadUtil;
import com.t.bricks.utils.spring.ModuleUtil;

/**
 * 代办事项备忘'WaitNote表'基本业务操作类接口实现
 */
@Service
public class WaitNoteServiceImpl implements WaitNoteService<WaitNote> {
	
	@Autowired
	private WaitNoteDao<WaitNote> waitNoteDao;
	
	/**
	 * 代通知对象缓存
	 */
	private Map<String, Map<String, WaitNoteSimpl>> waitNotePushCache;

	/**
	 * 推送信息
	 * @param printWriter
	 * @return
	 */
	@Override
	public void push(PrintWriter printWriter) {
		String userId = ModuleUtil.currentLoginUserId();
		
		initWaitNotePushCache(userId);//初始化代通知对象缓存
		
        while (true) {
        	ThreadUtil.sleepThread(1000);
       
            Date date = new Date();
       
            Map<String, WaitNoteSimpl> map = waitNotePushCache.get(userId);//有序
            Iterator<Map.Entry<String, WaitNoteSimpl>> it = map.entrySet().iterator();
            while(it.hasNext()) {
            	Map.Entry<String, WaitNoteSimpl> entry = it.next();
            	
            	long l = TimeUtil.difference(entry.getValue().getdEndDate(), date);
            	
            	if (l < 0) {//过期或下一秒后才通知的,不在这个循环进行
            		continue;
            	}

            	if (l < 0 || l > 2) {//过期或下一秒后才通知的,不在这个循环进行
            		continue;
            	}
            	
        		MsgEmity me = new MsgEmity(true, entry.getValue().getsId(), entry.getValue());
        		printWriter.write(JacksonShell.toJSONString(me));
        		printWriter.flush();
        		
                // 当浏览器页面关闭，检测pw flush断开后刷新异常，return进行断开sse
                if (printWriter.checkError()) {
                	Log.debug("客户端'", userId, "'断开连接");
                    return;
                }
        		
        		it.remove();//使用迭代器的remove()方法删除元素
            }

        }
	}
	
	/**
	 * 初始化代通知对象缓存
	 * @param sOwnerId
	 */
	private void initWaitNotePushCache(String sOwnerId) {
		synchronized (this) {
			if (null == waitNotePushCache) {
				waitNotePushCache = new HashMap<String,  Map<String, WaitNoteSimpl>>();
			}
		}
		
		Date dEndDateSt = new Date();
		Date dEndDateEd = TimeUtil.afterMinute(30, dEndDateSt);
		MsgEmity me = waitNoteDao.findByNotice(sOwnerId, dEndDateSt, dEndDateEd);
		if (!me.isSuccess()) {
			return;
		}
		
		List<WaitNoteSimpl> list = me.getData();
		if (null == list || list.size() < 1) {
			return;
		}
		
		Map<String, WaitNoteSimpl> map = waitNotePushCache.get(sOwnerId);
		if (null == map || map.size() < 1) {
			map = new LinkedHashMap<String, WaitNoteSimpl>();//有序
		}
		
		for (WaitNoteSimpl waitNoteSimpl : list) {
			map.put(waitNoteSimpl.getsId(), waitNoteSimpl);
		}
		
		waitNotePushCache.put(sOwnerId, map);
	}
	
}
